package com.bw.common.view

import android.os.Bundle
import android.util.Log
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.ViewModelProvider
import com.blankj.utilcode.util.ToastUtils
import com.bw.base.view.BaseActivity
import com.bw.common.entity.CustomEvent
import com.bw.common.vm.BaseViewModel
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.lang.reflect.ParameterizedType

abstract class BaseMvvmActivity<VDB:ViewDataBinding,VM:BaseViewModel>: BaseActivity<VDB>() {

    private val type by lazy { (javaClass.genericSuperclass as ParameterizedType).actualTypeArguments }

    //直接通过泛型拿到对应的ViewModel的class,来进行实例化
    protected val vm: VM by lazy {
        val clazz = type[1] as Class<VM>
        ViewModelProvider(this)[clazz]
    }

    open fun onError(t: Throwable) {
        ToastUtils.showLong(t.message)
        Log.e("TagA", "error:${t.message}")
        t.printStackTrace()
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        vm.onFailed.observe(this, ::onError)
        //注册EventBus事件总线
        EventBus.getDefault().register(this)
        super.onCreate(savedInstanceState)

    }

    /**
     * EventBus接收事件
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public fun onReceiveEvent(event: CustomEvent?){
        if (event != null && event.target == this.javaClass.simpleName){
            handEvent(event)
        }
    }

    protected open fun handEvent(event: CustomEvent){

    }



    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }




}